from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field, field_validator
from datetime import datetime
from .user import UserSchema
from .route import FlightRouteSchema
from .task_drone import TaskDroneSchema
from enum import Enum


class TaskPriorityEnum(str, Enum):
    """任务优先级枚举"""
    URGENT = "urgent"
    NORMAL = "normal"


class TaskStatusEnum(str, Enum):
    """任务状态枚举"""
    DRAFT = "draft"
    SCHEDULED = "scheduled"
    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    PAUSED = "paused"
    COMPLETED = "completed"
    CANCELLED = "cancelled"
    FAILED = "failed"


class TaskExecuteTypeEnum(str, Enum):
    """任务执行类型枚举"""
    IMMEDIATE = "immediate"
    SCHEDULED = "scheduled"
    MANUAL = "manual"


class TriggerCondition(BaseModel):
    """触发条件"""
    type: str = Field(..., description="触发类型")  # 如 "coordinate", "time", "manual"
    params: Dict[str, Any] = Field(..., description="触发参数")  # 如 {"lat": 39.9, "lng": 116.4, "radius": 50}


class ExceptionStrategy(BaseModel):
    """异常策略"""
    type: str = Field(..., description="异常类型")  # 如 "low_battery", "signal_loss", "detection_alert"
    action: str = Field(..., description="响应动作")  # 如 "return_home", "manual_takeover", "mark_location"
    params: Dict[str, Any] = Field(..., description="响应参数")  # 如 {"battery_threshold": 20}


class TaskRouteSchema(BaseModel):
    """任务航线关联"""
    id: int
    route_id: int
    order_index: int
    route: Optional[FlightRouteSchema] = None
    
    class Config:
        from_attributes = True


class TaskBase(BaseModel):
    """任务基础模型"""
    name: str = Field(..., min_length=1, max_length=200, description="任务名称")
    description: Optional[str] = Field(None, description="任务描述")
    priority: TaskPriorityEnum = Field(default=TaskPriorityEnum.NORMAL, description="优先级：紧急/普通")
    execute_type: TaskExecuteTypeEnum = Field(default=TaskExecuteTypeEnum.IMMEDIATE, description="执行类型：立即执行/定时执行")
    scheduled_time: Optional[datetime] = Field(None, description="计划执行时间")
    responsible_person_id: Optional[int] = Field(None, description="负责人ID")
    detection_model_ids: Optional[List[int]] = Field(None, description="绑定的检测模型ID列表")
    trigger_conditions: Optional[List[TriggerCondition]] = Field(None, description="触发条件配置")
    exception_strategies: Optional[List[ExceptionStrategy]] = Field(None, description="异常处理策略")
    route_coordinates: Optional[List[Dict[str, Any]]] = Field(None, description="航线坐标信息")


class TaskCreate(TaskBase):
    """创建任务请求模型"""
    route_ids: List[int] = Field(..., description="航线ID列表")
    route_order: Optional[List[int]] = Field(None, description="航线执行顺序，与route_ids一一对应")
    drone_ids: List[int] = Field(..., description="无人机ID列表")
    
    @field_validator('scheduled_time')
    @classmethod
    def validate_scheduled_time(cls, v, values):
        if values.data.get('execute_type') == TaskExecuteTypeEnum.SCHEDULED and not v:
            raise ValueError('定时执行任务必须指定计划执行时间')
        return v


class TaskUpdate(BaseModel):
    """更新任务请求模型"""
    name: Optional[str] = Field(None, min_length=1, max_length=200, description="任务名称")
    description: Optional[str] = Field(None, description="任务描述")
    priority: Optional[TaskPriorityEnum] = Field(None, description="优先级：紧急/普通")
    execute_type: Optional[TaskExecuteTypeEnum] = Field(None, description="执行类型：立即执行/定时执行")
    scheduled_time: Optional[datetime] = Field(None, description="计划执行时间")
    responsible_person_id: Optional[int] = Field(None, description="负责人ID")
    status: Optional[TaskStatusEnum] = Field(None, description="任务状态")
    detection_model_ids: Optional[List[int]] = Field(None, description="绑定的检测模型ID列表")
    trigger_conditions: Optional[List[TriggerCondition]] = Field(None, description="触发条件配置")
    exception_strategies: Optional[List[ExceptionStrategy]] = Field(None, description="异常处理策略")
    route_ids: Optional[List[int]] = Field(None, description="航线ID列表")
    route_order: Optional[List[int]] = Field(None, description="航线执行顺序")
    drone_ids: Optional[List[int]] = Field(None, description="无人机ID列表")
    progress: Optional[int] = Field(None, ge=0, le=100, description="任务进度（百分比）")


class TaskSchema(TaskBase):
    """任务响应模型"""
    id: int = Field(..., description="任务ID")
    status: Optional[TaskStatusEnum] = Field(default=TaskStatusEnum.DRAFT, description="任务状态")
    progress: Optional[int] = Field(default=0, description="任务进度（百分比）")
    start_time: Optional[datetime] = Field(None, description="开始执行时间")
    end_time: Optional[datetime] = Field(None, description="结束时间")
    created_by: Optional[int] = Field(None, description="创建人ID")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    
    # 关联信息
    responsible_person: Optional[UserSchema] = Field(None, description="负责人信息")
    task_routes: Optional[List[TaskRouteSchema]] = Field(None, description="任务航线信息")
    task_drones: Optional[List[TaskDroneSchema]] = Field(None, description="任务关联的无人机信息")
    
    class Config:
        from_attributes = True


class TaskList(BaseModel):
    """任务列表响应模型"""
    items: List[TaskSchema] = Field(..., description="任务列表")
    total: int = Field(..., description="总数")
    page: int = Field(..., description="当前页码")
    page_size: int = Field(..., description="每页大小")


class TaskStatusUpdate(BaseModel):
    """任务状态更新请求模型"""
    status: TaskStatusEnum = Field(..., description="任务状态")
    

class TaskProgressUpdate(BaseModel):
    """任务进度更新请求模型"""
    progress: int = Field(..., ge=0, le=100, description="任务进度（百分比）")